/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package conexion;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author Administrador
 */
public class SocketServer{
    private ServerSocket server;
    private Socket client;
    private SocketListener listener;
    private BufferedReader in;
    private PrintWriter out;
    private CommunicationThread comm;

    public SocketServer(int port, SocketListener listener){
        this.listener = listener;        
        listenSoket(port);
    }
    private void listenSoket(int port){
      System.out.println("entering listen socket");
      try{
         server = new ServerSocket(port); 
      } catch (IOException e) {
        System.out.println("Could not listen on port 4321");
        System.exit(-1);
      }        
      try{
        client = server.accept();
      } catch (IOException e) {
        System.out.println("Accept failed: "+port);
        System.exit(-1);
      }
      try{
       in = new BufferedReader(new InputStreamReader(client.getInputStream()));
       out = new PrintWriter(client.getOutputStream(),true);
      } catch (IOException e) {
        System.out.println("Read failed");
        System.exit(-1);
      }
      comm = new CommunicationThread(in, listener);
      comm.start();      
    }
    
    public void send(String data){
        System.out.println("enviando: "+data);
        out.println(data);
    }   
}
